package com.wjk.easy.blue;

import android.os.Handler;
import android.os.Message;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.wjk.easy.EasyApplication;
import com.wjk.easy.blue.FastBleService;
import com.wjk.easy.view.BlueScanListDialog;

import java.util.List;

public class FastBleDeviceManager {
    private BleManager bleManager;
    public FastBleDeviceManager() {
        bleManager = EasyApplication.getBluetoothClient();
        bleManager.init(EasyApplication.getAppContext());
        bleManager.enableLog(true)
                .setReConnectCount(1, 5000)
                .setConnectOverTime(20000)
                .setOperateTimeout(5000)
                  .setSplitWriteNum(20);
    }

    public boolean isSupportBle(){
        return bleManager.isSupportBle();
    }

    public boolean isBleOpen(){
        return bleManager.isBlueEnable();
    }

    public void startScan(final Handler handler){
        bleManager.scan(new BleScanCallback() {
            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                Message message = handler.obtainMessage(BlueScanListDialog.MSG_BLUE_SCAN_FINISH);
                message.obj = scanResultList;
                message.sendToTarget();
            }

            @Override
            public void onScanStarted(boolean success) {
                Message message = handler.obtainMessage(BlueScanListDialog.MSG_BLUE_SCAN_STARTED);
                message.obj = success;
                message.sendToTarget();
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                Message message = handler.obtainMessage(BlueScanListDialog.MSG_BLUE_SCANNING);
                message.obj = bleDevice;
                message.sendToTarget();
            }
        });
    }

    public void openBluetooth(){
        bleManager.enableBluetooth();
    }

    public void connect(BleDevice device, String deviceType) {
        blueConnectListener.setDeviceType(deviceType);
        bleManager.connect(device,blueConnectListener);
    }

    public void stopScan() {
        if(bleManager!=null)
            bleManager.cancelScan();
    }
    private FastBleService.BlueConnectListener blueConnectListener;
    public void setConnectStateListener(FastBleService.BlueConnectListener blueConnectListener) {
        this.blueConnectListener = blueConnectListener;
    }

    public void notifyScanCard(BleDevice device,String uuid_service,String uuid_notify, BleNotifyCallback callback) {
        bleManager.notify(device,uuid_service,uuid_notify,callback);
    }
}
